<script setup lang="ts">
import { PlusSearch, type PlusColumn } from "plus-pro-components";
import "plus-pro-components/es/components/search/style/css";
import { ref } from "vue";
import { useColumns } from "./columns";
import { utils, writeFile } from "xlsx";
import { getFlowList } from "@/api/user";
import { formatDate } from "@/utils/common";
import { ElMessage } from "element-plus";
defineOptions({
  name: "UserFlow"
});
import { useMenu } from "@/utils/power";
const power = useMenu(["exportExcel"]);
const searchColumns: PlusColumn[] = [
  {
    label: "账号",
    width: 200,
    prop: "account",
    valueType: "input",
    fieldProps: {
      controls: false
    },
    tooltip: "请输入搜索用户账号"
  },
  {
    label: "订单ID",
    width: 200,
    prop: "orderId",
    valueType: "input-number",
    fieldProps: {
      controls: false
    },
    tooltip: "请输入搜索订单ID"
  },
  {
    label: "支付方式",
    width: 100,
    labelWidth: 120,
    prop: "wallet",
    valueType: "select",
    options: [
      { label: "余额", value: 0 },
      { label: "收益", value: 1 },
      { label: "积分", value: 2 },
      { label: "消费券", value: 3 }
    ]
  },
  {
    label: "流水类型",
    width: 100,
    labelWidth: 120,
    prop: "type",
    valueType: "select",
    options: [
      { label: "购买设备产品", value: 0 },
      { label: "管理直推收益", value: 1 },
      { label: "管理平级收益", value: 2 },
      { label: "管理收益", value: 3 },
      { label: "转账", value: 4 },
      { label: "节点分红", value: 5 },
      { label: "流量等级收益(设备等级)", value: 6 },
      { label: "直推流量收益", value: 7 },
      { label: "平级流量收益", value: 8 },
      { label: "流量收益", value: 9 },
      { label: "后台操作", value: 10 },
      { label: "提现", value: 11 },
      { label: "转账", value: 12 },
      { label: "领取流水收益", value: 13 },
      { label: "充值", value: 14 },
      { label: "购买商品", value: 15 },
      { label: "合伙人收益", value: 16 },
      { label: "参与盲盒", value: 17 },
      { label: "定投(购买算力下单)", value: 18 },
      { label: "定投收益(算力回报金额)", value: 19 },
      { label: "收益到期退回", value: 20 },
      { label: "用户购买买商品下单", value: 21 },
      { label: "用户下单购买会议或者旅游产品下单", value: 22 },
      { label: "会议或者旅游产品下单退回", value: 23 },
      { label: "完成任务，领取奖励", value: 23 },
      { label: "提现添加", value: 24 }
    ]
  },
  {
    label: "是否本月",
    prop: "thisMonth",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0
      },
      {
        label: "是",
        value: 1
      }
    ]
  },
  {
    label: "选择时间范围",
    labelWidth: 120,
    width: 600,
    prop: "dateRange",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "daterange",
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      disabledDate: (time: any) => {
        if (searchValue.value.thisMonth == 1) {
          // 近30日可选
          return (
            time.getTime() > Date.now() ||
            time.getTime() < Date.now() - 30 * 24 * 60 * 60 * 1000
          );
        }
        return time.getTime() > Date.now() - 30 * 24 * 60 * 60 * 1000;
      }
    }
  }
];

const defaultSearchState = ref({ thisMonth: 1 });
const searchValue = ref({ thisMonth: 1 });

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  loadData,
  params,
  onKeywordChange,
  onCurrentChange
} = useColumns();

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "account" || target.prop == "orderId") {
    return;
  }

  onKeywordChange(value);
};

const fullscreenLoading = ref(false);

const exportExcel = async () => {
  try {
    const postData = Object.assign({}, params.value);
    postData.pageSize = 5;
    postData.page = 1;
    const resData = await getFlowList(postData);
    const data = resData.data.items;

    const dataKeys: string[] = [
      "reId",
      "flowCode",
      "account",
      "content",
      "revenueStatus",
      "overMoney",
      "overScore",
      "overIntegral",
      "overCoupon",
      "money",
      "wallet",
      "type",
      "createdAt"
    ];
    const titleList: string[] = [
      "流水ID",
      "流水编号",
      "账号",
      "内容",
      "是否领取",
      "余额",
      "收益",
      "积分",
      "优惠点",
      "金额",
      "支付方式",
      "流水类型",
      "时间"
    ];
    const res: string[][] = data.map(item => {
      const arr = [];
      item.money = (item.status == "1" ? "-" : "+") + item.money;
      item.revenueStatus = item.revenueStatus == 1 ? "已领取" : "未领取";
      item.wallet = (() => {
        switch (Number(item.wallet)) {
          case 0:
            return "余额";
          case 1:
            return "收益";
          case 2:
            return "积分";
          case 3:
            return "消费券";
          default:
            return "未知";
        }
      })();
      item.type = (() => {
        switch (Number(item.type)) {
          case 0:
            return "购买设备产品";
          case 1:
            return "管理直推收益";
          case 2:
            return "管理平级收益";
          case 3:
            return "管理收益";
          case 4:
            return "转账";
          case 5:
            return "节点分红";
          case 6:
            return "流量等级收益(设备等级)";
          case 7:
            return "直推流量收益";
          case 8:
            return "平级流量收益";
          case 9:
            return "流量收益";
          case 10:
            return "后台操作";
          case 11:
            return "提现";
          case 12:
            return "转账";
          case 13:
            return "领取流水收益";
          case 14:
            return "充值";
          case 15:
            return "购买商品";
          case 16:
            return "合伙人收益";
          case 17:
            return "参与盲盒";
          case 18:
            return "定投(购买算力下单)";
          case 19:
            return "定投收益(算力回报金额)";
          case 20:
            return "收益到期退回";
          case 21:
            return "用户购买买商品下单";
          case 22:
            return "用户下单购买会议或者旅游产品下单";
          case 23:
            // 处理值为 23 的两种情况
            return "会议或者旅游产品下单退回/完成任务，领取奖励";
          case 24:
            return "提现添加";
          default:
            return "未知";
        }
      })();
      dataKeys.forEach(column => {
        arr.push(item[column]);
      });
      return arr;
    });
    res.unshift(titleList);
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `${formatDate(new Date())} 个人流水报表.xlsx`);
    ElMessage.success(`导出成功${data.length}条`);
  } catch (error) {
    console.log(error, "exportError");
  }
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>个人流水</h3>
        </template>
        <template v-if="power.exportExcel" #extra>
          <el-popconfirm
            title="是否确认导出(默认导出最大5000条数据)"
            @confirm="exportExcel"
          >
            <template #reference>
              <el-button
                v-loading.fullscreen.lock="fullscreenLoading"
                type="primary"
                size="default"
                class="mb-4!"
              >
                导出Excel
              </el-button>
            </template>
          </el-popconfirm>
        </template>
        <PlusSearch
          v-model="searchValue"
          :default-values="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @search="handleSearch"
          @change="handleChange"
          @reset="handleReset"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      :adaptive="false"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    />
  </ElCard>
</template>

<style scoped></style>
